package com.http.client;

import android.os.*;
import android.os.Process;

import com.http.HttpFactory;
import com.http.method.Request;

import org.apache.http.conn.ConnectTimeoutException;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.UnknownHostException;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created by mac_wk on 14-12-16.
 */
public class RequestProcessor extends Thread{
    private PriorityBlockingQueue<Request<?>> priorityBlockingQueue = null;
    public RequestProcessor(PriorityBlockingQueue<Request<?>> mNetworkQueue) {
            this.priorityBlockingQueue = mNetworkQueue;
    }

    @Override
    public void run() {
        super.run();
        android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true)
        {
            Request request = null;
            try {
                request = priorityBlockingQueue.take();
                HttpURLConnection httpURLConnection = HttpFactory.createHttp(request);
                httpURLConnection.connect();
                request.executeRequest(httpURLConnection);
                httpURLConnection.disconnect();
            }
            catch (ConnectTimeoutException  e)
            {
                e.printStackTrace();
                //链接超时 进行重试操作
                if (request.retry>0)
                {
                    request.retry--;
                    priorityBlockingQueue.add(request);
                }
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
